<?php
/**
 * @author GhostWei
 * @date Sep 16, 2012
 */
class resource_api_avatar extends resource_api_abstract {
	
	public static function create($src, $rigorous = false) {
		$thumb = self::check($src);
		
		if(!is_array($rigorous)) {
			throw new resource_exception("Params error");
		}
		$params = self::setParams($rigorous);
		$cDim = $thumb->getCurrentDimensions();
		$cDim['width'] = $cDim['width'] * $params['p'];
		$cDim['height'] = $cDim['height'] * $params['p'];
		$temName = $src['tmp_name'] . '.cache';
		$img = $thumb->loadImage()->resize($cDim['width'], $cDim['height'])->save($temName);
		
		$thumb->setFileName($temName);
		$thumb->loadImage()->crop($params['x'], $params['y'], $params['w'], $params['h'])->save($temName);
				
		$content = file_get_contents($temName);
		$thumb->setFileName($temName);
		$ext = strtolower($thumb->getFormat());
		$cDim = $thumb->getCurrentDimensions();
		$md5 = system_file_io::md5Filename(null, $content);
		$md5code = resource_config_avatar::md5Path($md5);
		$md5file = resource_config_avatar::dir() . $md5code;
		$md5name = '/original.' . $ext;
		if(!file_exists($md5file . $md5name)) {
			system_file_io::mkdir($md5file);
			if(!file_put_contents($md5file . $md5name, $content)) {
				throw new resource_exception("Save avatar faild,Please check if the folder is writable.");
			}
		}
		try {
			$row = self::saveToDatabase(array(
					'hash' => $md5, 
					'size' => $src['size'], 
					'ext' => $ext, 
					'dimension' => $cDim
				), 'avatar');
			if(!parent::$_isInDtabase) {
				foreach(resource_config_avatar::getSizes() AS $key => $name) {
					$image = $thumb->loadImage()->resize($key);
					$image->save($md5file . '/' . $name . '.' . $ext);
				}
				@unlink($temName);
				@unlink($src['tmp_name']);
			}
			return $row;
		} catch (Exception $ex) {
			if(!parent::$_isInDtabase) {
				@unlink($md5file . $md5name);
				foreach(resource_config_avatar::getSizes() AS $key => $name) {
					@unlink($md5file . '/' . $name . '.' . $ext);
				}
			}
			throw $ex;
		}
	}
	
	public static function createRemote($http) {
		$src = parent::saveRemoteToLocal($http);
		$thumb = self::check($src);
		$cDim = $thumb->getCurrentDimensions();
		$cDim['width'] = intval($cDim['width']);
		$cDim['height'] = intval($cDim['height']);
		return self::create($src, self::setParams(array('w' => $cDim['width'], 'h' => $cDim['height'])));
	}

	/**
	 * @return system_image_thumbGd
	 */
	public static function createTemp($src, $save = true) {
		$thumb = self::check($src);
		$cDim = $thumb->getCurrentDimensions();
		$cDim['width'] = intval($cDim['width']);
		$cDim['height'] = intval($cDim['height']);
		
		$min = resource_config_avatar::getMinDimension();
		$min['width'] = intval($min['width']);
		$min['height'] = intval($min['height']);
		if($cDim['width'] < $min['width'] && $cDim['height'] < $min['height']) {
			throw new resource_exception("This image is too small,please more than {$min['width']} x {$min['height']}.");
		}
		if($save) {
			$filename = self::getTempFileName();
			$content = file_get_contents($src['tmp_name']);
			if(!file_put_contents($filename, $content)) {
				throw new resource_exception("Save avatar faild,Please check if the folder is writable.");
			}
		}
		return $thumb;
	}
	
	/**
	 * @return system_image_thumbGd
	 */
	protected static function check($src) {
		if(empty($src)) {
			throw new resource_exception("Image is empty.");
		}
		$content = file_get_contents($src['tmp_name']);
		if(!$content) {
			throw new resource_exception("Image is empty.");
		}
		$thumb = system_image_factory::create($src['tmp_name']);
		$ext = strtolower($thumb->getFormat());
		$filter = resource_config_avatar::getExtensions();
		if(empty($ext) || !in_array($ext, $filter)) {
			throw new resource_exception("Avatar type is not suppoted,it should be a(n) '" . implode(',', $filter) . "' file.");
		}
		return $thumb;
	}
	
	public static function getTempFileName() {
		$filename = _DIRECTORY_VAR . DIRECTORY_SEPARATOR . 'tmp' . 
				DIRECTORY_SEPARATOR . 'avatar' . DIRECTORY_SEPARATOR . system_session::getId() . '.tmp';
		system_file_io::mkdir(dirname($filename));
		return $filename;
	}
	
	protected static function setParams($p) {
		$params = array();
		$md = resource_config_avatar::getMinDimension();
		$params['p'] = !isset($p['p']) ? 1 : floatval($p['p']);
		$params['x'] = !isset($p['x']) ? 0 : intval($p['x']);
		$params['y'] = !isset($p['y']) ? 0 : intval($p['y']);
		$params['w'] = !isset($p['w']) ? $md['width'] : intval($p['w']);
		$params['h'] = !isset($p['h']) ? $md['height'] : intval($p['h']);
		return $params;
	}
}
